package net.wang.concurrency.test.sync;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class SynchronizedExample1 {


    public void test1() {
        synchronized (this) {
            for (int i = 0; i < 10; i++) {
                log.info("test===1 {}", i);
            }
        }
    }


    public synchronized void test2() {
        for (int i = 0; i < 10; i++) {
            log.info("test===2 {}", i);
        }
    }

    public static void safeTest() {
        SynchronizedExample1 example1 = new SynchronizedExample1();
        ExecutorService executorService = Executors.newCachedThreadPool();

        executorService.execute(() -> example1.test1());
        executorService.execute(() -> example1.test2());
    }


    /**
     * 输出结果  交替 ，说明synchronized 关键字作用与当前对象，适合与单例模式的某个方法线程安全
     * 注意：子类继承父类的 synchronized 关键字方法不起作用，是因为synchronized不属于方法声明的一部分
     */
    public static void notSafeTest() {
        SynchronizedExample1 example1 = new SynchronizedExample1();
        SynchronizedExample1 example2 = new SynchronizedExample1();
        ExecutorService executorService = Executors.newCachedThreadPool();

        executorService.execute(() -> example1.test1());
        executorService.execute(() -> example2.test2());
    }

    public static void main(String[] args) {
        //safeTest();
        notSafeTest();
    }
}
